package cn.bdqn.service.impl;

import cn.bdqn.dto.Dto;
import cn.bdqn.pojo.User;
import cn.bdqn.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/8/17.
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SimpleMailMessage mailMessage;
    @Resource
    private JavaMailSender mailSender;
    @Override
    public Dto regdit(User user) {
        //接收到用户注册信息
        //调用dao进行持久化操作 userMapper.insertUser
        //密码加密 md5加密不可逆 撞库 结果不是有效 对象。方法（参数）
        user.setId(1);
        user.setPassword("123456");
        user.setUsername("admin");
        user.setBirthday(new Date());
        Dto dto = new Dto();
        dto.setCode("10086");
        dto.setMsg("注册成功");
        //将结果封装在dto里
        dto.setData(user);
        //生成验证码 UUID生成对象.方法
        String code = UUID.randomUUID().toString();
        //保存redis
        //redis操作 StringRedisTemplate 有效期
        stringRedisTemplate.opsForValue().set("active:"+user.getUsername(), code,20, TimeUnit.MINUTES);
        //发送邮件到用户邮箱
        stringRedisTemplate.opsForHash().put("user",User.class,user);
        mailMessage.setTo(user.getUsername());
        mailMessage.setText("你的激活码是："+code);
        mailSender.send(mailMessage);
        stringRedisTemplate.opsForValue().get("active:"+user.getUsername());
        System.out.println("取出来的激活码是："+stringRedisTemplate.opsForValue().get("active:"+user.getUsername()));
        redisTemplate.opsForHash().put("user",User.class,user);
        User user1= (User) stringRedisTemplate.opsForHash().get("user",User.class);
        System.out.println("取出来的用户名是"+user1.getUsername());
        return dto;
    }
}
